Factory Pattern

1 min read
Foundational1 min read
Rapid overview

Factory Pattern

TL;DR

Provide a single place to create related objects without exposing construction details.

Why it matters

  • Centralizes creation logic for shared dependencies.
  • Makes testing easier by swapping factories.
  • Helps enforce consistent configuration.

How it works


Example (TypeScript)

type ApiClient = { get: (path: string) => Promise<unknown> };

type ClientConfig = { baseUrl: string; token?: string };

const createApiClient = ({ baseUrl, token }: ClientConfig): ApiClient => ({
  get: (path) =>
    fetch(`${baseUrl}${path}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : undefined
    }).then((res) => res.json())
});

Quick recall Q&A

Q: When do you use a factory? A: When object creation requires configuration, caching, or runtime selection.
Q: Factory vs Builder? A: Factory returns a ready instance; Builder assembles complex objects step-by-step.

See also